<template>
  <div class="mobile-upload-container">
    <!-- 返回按钮和标题 -->
    <van-nav-bar title="古建筑彩绘文物调查管理系统" left-arrow @click-left="onClickLeft" @click-right="goToUser" fixed>

      <!-- 右侧用户图标 -->
      <template #right>
        <van-icon name="user" size="18" />
      </template>
    </van-nav-bar>
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <span class="breadcrumb-item" @click="goHome">首页</span>
      <span class="breadcrumb-separator">></span>
      <span class="breadcrumb-item" @click="goToCategory">文物主体管理</span>
      <span class="breadcrumb-separator">></span>
      <span class="breadcrumb-item" @click="gomainpage">{{ formData.culturalRelic.category_name }}</span>
      <span class="breadcrumb-separator">></span>
      <span class="breadcrumb-item">{{ formData.culturalRelic.name }}</span>
      <span class="breadcrumb-separator">></span>
      <span class="breadcrumb-item">编辑</span>
    </div>

    <van-form ref="formRef" class="upload-form" @submit="onSubmit" @failed="onFailed">
      <!-- 基本信息 -->
      <van-cell-group title="基本信息" inset>
        <!-- 名称 -->
        <van-field v-model="formData.culturalRelic.name" name="name" :label="''" placeholder="请输入文物名称"
          :rules="[{ required: true, message: '请输入名称' }]">
          <template #label>
            <span class="required-label">名称</span>
          </template>
        </van-field>
        <!-- 主图 -->
        <van-field>
          <!-- 标签 -->
          <template #label>
            <span class="required-label">主图</span>
          </template>

          <!-- 所有内容都放在 #input 插槽内 -->
          <template #input>
            <div style="display: flex; align-items: center; gap: 10px;">
              <!-- 显示当前主图 -->
              <van-image v-if="currentRelic.image_base64 || currentRelic.image" width="100" height="100"
                :src="currentRelic.image_base64 || currentRelic.image" fit="cover" style="flex-shrink: 0;" />

              <!-- 上传器 -->
              <van-uploader v-model="formData.culturalRelic.image" :max-count="1" :before-read="beforeImageRead"
                upload-text="更换图片" @delete="handleRemove" />
            </div>
          </template>
        </van-field>

        <!-- 彩画做法 -->
        <van-field v-model="formData.culturalRelic.painting_technique" name="painting_technique" :label="''"
          type="textarea" rows="3" autosize placeholder="例如：仪门月梁侧面两端雕龙凤等吉祥图案，中部则雕刻戏曲人物。"
          :rules="[{ required: true, message: '请输入彩画做法' }]">
          <template #label>
            <span class="required-label">彩画做法</span>
          </template>
        </van-field>
      </van-cell-group>

      <!-- 纹样信息 -->
      <van-cell-group title="纹样信息" inset>
        <!-- 纹样类型 -->
        <van-field name="pattern_types" label="''" :rules="[
          { validator: validatePatternType, message: '请至少选择一个纹样类型', required: true }
        ]">
          <template #label>
            <span class="required-label">纹样类型</span>
          </template>
          <template #input>
            <van-checkbox-group v-model="formData.culturalRelic.pattern_types" direction="horizontal">
              <van-checkbox name="几何纹">几何纹</van-checkbox>
              <van-checkbox name="花卉纹">花卉纹</van-checkbox>
              <van-checkbox name="动物纹">动物纹</van-checkbox>
              <van-checkbox name="人物故事">人物故事</van-checkbox>
              <van-checkbox name="山水">山水</van-checkbox>
              <van-checkbox name="文字">文字</van-checkbox>
              <van-checkbox name="宗教符号">宗教符号</van-checkbox>
              <van-checkbox name="植物纹">植物纹</van-checkbox>
              <van-checkbox name="石雕纹样">石雕纹样</van-checkbox>
              <van-checkbox name="螭龙纹">螭龙纹</van-checkbox>
              <van-checkbox name="卷草纹">卷草纹</van-checkbox>
              <van-checkbox name="麒麟">麒麟</van-checkbox>
              <van-checkbox name="凤凰">凤凰</van-checkbox>
              <van-checkbox name="other">其他</van-checkbox>
            </van-checkbox-group>
          </template>
        </van-field>

        <!-- 其他纹样 -->
        <van-field v-if="formData.culturalRelic.pattern_types.includes('other')"
          v-model="formData.culturalRelic.other_pattern_types" label="其他纹样" placeholder="请输入其他纹样类型" :rules="[
            { required: true, message: '当选择其他时，请输入其他纹样类型' }
          ]" />

        <!-- 彩画主题 -->
        <van-field v-model="formData.culturalRelic.painting_theme" name="painting_theme" :label="''"
          placeholder="如“龙凤呈祥”“缠枝莲纹”等" :rules="[{ required: true, message: '请输入彩画主题' }]">
          <template #label>
            <span class="required-label">彩画主题</span>
          </template>
        </van-field>
        <!-- 构图形式 -->
        <van-field label="''" :rules="[
          { validator: validatePatternType, message: '请至少选择一个构图形式', required: true }
        ]">
          <template #label>
            <span class="required-label">构图形式</span>
          </template>
          <template #input>
            <van-checkbox-group v-model="formData.culturalRelic.composition_style" direction="horizontal">
              <van-checkbox name="对称式">对称式</van-checkbox>
              <van-checkbox name="自由式">自由式</van-checkbox>
              <van-checkbox name="分段式">分段式</van-checkbox>
              <van-checkbox name="other">其他</van-checkbox>
            </van-checkbox-group>
          </template>
        </van-field>

        <van-field v-if="formData.culturalRelic.composition_style.includes('other')"
          v-model="formData.culturalRelic.other_composition_style" label="其他构图" placeholder="请输入其他构图形式" :rules="[
            { required: true, message: '当选择其他时，请输入其他构图形式' }
          ]" />

        <!-- 主色调 -->
        <van-field label="''" :rules="[
          { validator: validatePatternType, message: '请至少选择一个主色调', required: true }
        ]">
          <template #label>
            <span class="required-label">主色调</span>
          </template>
          <template #input>
            <van-checkbox-group v-model="formData.culturalRelic.dominant_colors" direction="horizontal">
              <van-checkbox name="蓝">蓝</van-checkbox>
              <van-checkbox name="绿">绿</van-checkbox>
              <van-checkbox name="红">红</van-checkbox>
              <van-checkbox name="浅绿">浅绿</van-checkbox>
              <van-checkbox name="黄">黄</van-checkbox>
              <van-checkbox name="黑">黑</van-checkbox>
              <van-checkbox name="地仗">地仗</van-checkbox>
              <van-checkbox name="褐色">褐色</van-checkbox>
              <van-checkbox name="金">金</van-checkbox>
              <van-checkbox name="深蓝">深蓝</van-checkbox>
              <van-checkbox name="紫色">紫色</van-checkbox>
              <van-checkbox name="other">其他</van-checkbox>
            </van-checkbox-group>
          </template>
        </van-field>

        <van-field v-if="formData.culturalRelic.dominant_colors.includes('other')"
          v-model="formData.culturalRelic.other_dominant_colors" label="其他色调" placeholder="请输入其他主色调" :rules="[
            { required: true, message: '当选择其他时，请输入其他构图形式' }
          ]" />
      </van-cell-group>

      <!-- 病害情况 -->
      <van-cell-group title="病害情况" inset>
        <van-field label="''" :rules="[
          { validator: validatePatternType, message: '请至少选择一种病害类型', required: true }
        ]">
          <template #label>
            <span class="required-label">病害类型</span>
          </template>
          <template #input>
            <van-checkbox-group v-model="formData.culturalRelic.disease_types" direction="horizontal">
              <van-checkbox name="裂隙">裂隙</van-checkbox>
              <van-checkbox name="龟裂">龟裂</van-checkbox>
              <van-checkbox name="起翘">起翘</van-checkbox>
              <van-checkbox name="酥解">酥解</van-checkbox>
              <van-checkbox name="空鼓">空鼓</van-checkbox>
              <van-checkbox name="剥离">剥离</van-checkbox>
              <van-checkbox name="地仗脱落">地仗脱落</van-checkbox>
              <van-checkbox name="颜料剥落">颜料剥落</van-checkbox>
              <van-checkbox name="金层剥落">金层剥落</van-checkbox>
              <van-checkbox name="粉化">粉化</van-checkbox>
              <van-checkbox name="变色">变色</van-checkbox>
              <van-checkbox name="积尘">积尘</van-checkbox>
              <van-checkbox name="结垢">结垢</van-checkbox>
              <van-checkbox name="油烟污损">油烟污损</van-checkbox>
              <van-checkbox name="动物损害">动物损害</van-checkbox>
              <van-checkbox name="水渍">水渍</van-checkbox>
              <van-checkbox name="微生物损害">微生物损害</van-checkbox>
              <van-checkbox name="人为污染">人为污染</van-checkbox>
              <van-checkbox name="其他污染">其他污染</van-checkbox>
            </van-checkbox-group>
          </template>
        </van-field>

        <!-- 人为污染详情 -->
        <van-field v-if="formData.culturalRelic.disease_types.includes('人为污染')"
          v-model="formData.culturalRelic.human_pollution_details" label="人为污染" placeholder="刻画/涂鸦/附加管线等" :rules="[
            { required: true, message: '当选择人为污染时，请输入人为污染情况' }
          ]" />

        <!-- 其他污染详情 -->
        <van-field v-if="formData.culturalRelic.disease_types.includes('其他污染')"
          v-model="formData.culturalRelic.other_pollution_details" label="其他污染" placeholder="油漆/涂料/沥青等" :rules="[
            { required: true, message: '当选择其他污染时，请输入其他污染情况' }
          ]" />
        <!-- 病害程度 -->
        <van-field :label="''" :rules="[{ required: true, message: '请选择病害程度' }]">
          <template #label>
            <span class="required-label">病害程度</span>
          </template>
          <template #input>
            <van-radio-group v-model="formData.culturalRelic.disease_severity">
              <van-radio name="轻微">轻微（&lt;10%）</van-radio>
              <van-radio name="中度">中度（10%-50%）</van-radio>
              <van-radio name="严重">严重（&gt;50%）</van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <!-- 情况描述 -->
        <van-field v-model="formData.culturalRelic.current_damage_status" name="current_damage_status" :label="''"
          type="textarea" rows="3" autosize placeholder="描述当前文物的残损部位及状态"
          :rules="[{ required: true, message: '请输入现状描述' }]">
          <template #label>
            <span class="required-label">情况描述</span>
          </template>
        </van-field>

        <!-- 添加图片按钮 -->
        <van-field label="图像">
          <template #input>
            <van-button type="primary" size="small" @click="openAddImageDialog">添加图片</van-button>
          </template>
        </van-field>

        <!-- 已上传图片列表 -->
        <div class="image-list">
          <div v-for="(item, index) in formData.culturalRelic.disease_image" :key="index" class="image-item">
            <van-image width="80" height="80" :src="item.url" fit="cover" @click="() => handleImagePreview(item.url)" />
            <div class="image-info">
              <div><strong>图像名称：</strong>{{ item.image_name || '未命名' }}</div>
              <div><small>图像描述：{{ item.description || '无' }}</small></div>
              <div><small>上传时间：{{ item.created_at || '无' }}</small></div>
            </div>
            <div class="image-actions">
              <van-icon name="edit" @click="editImage(index, item.id)" />
              <van-icon name="delete" @click="removeImage(index, item.id)" />
            </div>
          </div>
        </div>
      </van-cell-group>

      <!-- 光谱与三维数据 -->
      <!-- 光谱与三维数据 -->
      <van-cell-group title="数据文件" inset>
        <!-- 是否采集光谱图像 -->
        <van-field label="光谱图像：">
          <template #input>
            <span :class="formData.culturalRelic.hasSpectrum === 'true' ? 'status-yes' : 'status-no'">
              {{ formData.culturalRelic.hasSpectrum === 'true' ? '已采集' : '未采集' }}
              <div class="upload-hint">请前往电脑端上传或修改。</div>
            </span>
          </template>
        </van-field>

        <!-- 是否采集三维图像 -->
        <van-field label="三维图像：">
          <template #input>
            <span :class="formData.culturalRelic.hasThreeD === 'true' ? 'status-yes' : 'status-no'">
              {{ formData.culturalRelic.hasThreeD === 'true' ? '已采集' : '未采集' }}
              <div class="upload-hint">请前往电脑端上传或修改。</div>
            </span>
          </template>
        </van-field>
      </van-cell-group>

      <!-- 提交按钮 -->
      <div class="form-actions">
        <van-button round block type="primary" native-type="submit" :loading="loading">
          保存修改
        </van-button>
        <van-button round block @click="handleCancel">取消</van-button>
      </div>
    </van-form>

    <!-- 图片预览 -->
    <van-image-preview v-model:show="previewVisible" :images="previewImages" />

    <!-- 添加/编辑图片弹窗 -->
    <van-popup v-model:show="imageDialogVisible" position="bottom" round closeable>
      <div class="image-dialog">
        <h3 class="dialog-title">{{ isEditing ? '修改图片' : '添加图片' }}</h3>
        <el-form-item label="图片" required>
          <van-uploader v-model="tempImage.fileList" :max-count="1" :after-read="onTempImageRead"
            @delete="handleTempRemove" />
        </el-form-item>
        <!-- 名称 -->
        <el-form-item label="名称" required>
          <van-field v-model="tempImage.customName" placeholder="如：戏台藻井东"
            :rules="[{ required: true, message: '请输入名称' }]">
          </van-field>
        </el-form-item>
        <!-- 描述 -->
        <el-form-item label="描述">
          <van-field v-model="tempImage.description" type="textarea" rows="2" autosize placeholder="位于东墙中部，长约30cm" />
        </el-form-item>
        <div style="padding: 16px;">
          <van-button round block type="primary" @click="confirmImage">确认</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { showSuccessToast, showFailToast, showConfirmDialog, showToast } from 'vant'

import { useEdit } from '@/components/composables/useEdit'
const {
  loading,
  error,
  currentRelic,
  formRef,
  formData,
  imageChanged,
  goHome,
  goToUser,
  goToCategory,
  gomainpage,
  fetchRelicData,
  onClickLeft,
  onSubmit,
  handleCancel,
  handleDeleteImage,
} = useEdit()

// ===== 图片预览 =====
const previewVisible = ref(false)
const previewImages = ref<string[]>([])

const handleImagePreview = (url: string) => {
  previewImages.value = [url]
  previewVisible.value = true
}

// ===== 表单校验 =====
const validatePatternType = (value: any[]) => {
  return Array.isArray(value) && value.length > 0
}

const beforeImageRead = (file: File) => {
  if (file.type.startsWith('image/')) return true
  showToast('请上传图片文件')
  return false
}

const handleRemove = () => {
  // 可在此释放 blob URL（如果需要）
}

// ===== 临时图片弹窗逻辑 =====
const imageDialogVisible = ref(false)
const isEditing = ref(false)
const editingIndex = ref(-1)

const tempImage = ref({
  fileList: [] as { url: string; file: File }[],
  customName: '',
  description: '',
  id: null as number | null
})

// 清除临时 blob URL
const handleTempRemove = () => {
  tempImage.value.fileList.forEach(item => {
    if (item.url.startsWith('blob:')) {
      URL.revokeObjectURL(item.url)
    }
  })
  tempImage.value.fileList = []
}

// 读取新图片
const onTempImageRead = (file: { content: string; file: File }) => {
  const url = URL.createObjectURL(file.file)
  tempImage.value.fileList = [{ url, file: file.file }]
}

// 打开添加弹窗
const openAddImageDialog = () => {
  isEditing.value = false
  editingIndex.value = -1
  handleTempRemove()
  tempImage.value = { fileList: [], customName: '', description: '', id: null }
  imageDialogVisible.value = true
}

// 编辑图片
const editImage = (index: number, id: number) => {
  const item = formData.culturalRelic.disease_image[index]

  // 释放旧的 blob URL
  handleTempRemove()

  // 如果已有 file 和 url，直接使用
  if (item.file && item.url) {
    tempImage.value.fileList = [{ url: item.url, file: item.file }]
  } else {
    // 否则尝试从 base64 转（兼容旧数据）
    if (item.url?.startsWith('data:image')) {
      const arr = item.url.split(',')
      const mime = arr[0].match(/:(.*?);/)![1]
      const bstr = atob(arr[1])
      const u8arr = new Uint8Array(bstr.length)
      for (let i = 0; i < bstr.length; i++) {
        u8arr[i] = bstr.charCodeAt(i)
      }
      const blob = new Blob([u8arr], { type: mime })
      const file = new File([blob], 'image.jpg', { type: mime })
      const url = URL.createObjectURL(blob)
      tempImage.value.fileList = [{ url, file }]
    } else {
      tempImage.value.fileList = [{ url: item.url, file: undefined! }]
    }
  }

  tempImage.value.customName = item.image_name || ''
  tempImage.value.description = item.description || ''
  tempImage.value.id = id

  isEditing.value = true
  editingIndex.value = index
  imageDialogVisible.value = true
}

// 删除图片
const removeImage = (index: number, id: number) => {
  showConfirmDialog({
    title: '删除图片',
    message: '确定要删除这张图片吗？',
  }).then(() => {
    // 实际项目中需要调用API删除
    // handleDeleteImage(currentRelic.value.id, id)
    formData.culturalRelic.disease_image.splice(index, 1)
    showToast('删除成功')
  }).catch(() => { })
}

// 确认添加或编辑
const confirmImage = () => {
  const { fileList, customName, description } = tempImage.value
  if (!fileList.length) {
    showToast('请上传图片')
    return
  }
  if (!customName.trim()) {
    showToast('请输入图片名称')
    return
  }

  const { file, url } = fileList[0]

  const imageObj = {
    file,
    url,
    image_name: customName,
    description,
    id: tempImage.value.id // 保留ID用于编辑
  }

  if (isEditing.value && editingIndex.value !== -1) {
    formData.culturalRelic.disease_image.splice(editingIndex.value, 1, imageObj)
  } else {
    formData.culturalRelic.disease_image.push(imageObj)
  }

  imageDialogVisible.value = false
  showToast(isEditing.value ? '修改成功' : '添加成功')
}

// 表单验证失败
const onFailed = () => {
  showFailToast('请完善必填信息')
}
</script>

<style scoped>
.mobile-upload-container {
  padding-top: 46px;
  min-height: 100vh;
  background-color: #f7f8fa;
}

.upload-form {
  padding: 10px 0;
}

.form-actions {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.image-list {
  padding: 10px;
}

.image-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding: 10px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.image-info {
  flex: 1;
  margin-left: 10px;
  font-size: 14px;
  color: #333;
}

.image-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.image-actions .van-icon {
  font-size: 18px;
  cursor: pointer;
}

.image-dialog {
  padding: 16px;
}

.dialog-title {
  font-size: 18px;
  margin: 16px 0;
  text-align: center;
}

.required-label::before {
  content: '*';
  color: red;
  margin-right: 4px;
}

/* 面包屑样式 */
.breadcrumb {
  padding: 8px 16px;
  background-color: #f7f8fa;
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
  /* 确保不被 fixed 的 nav-bar 遮挡 */
  margin-top: 0px;
  /* van-nav-bar 的默认高度 */
}

.breadcrumb-item {
  color: #1989fa;
  /* 可点击项用蓝色 */
}

.breadcrumb-item:last-child {
  color: #333;
  font-weight: 500;
}

.breadcrumb-separator {
  margin: 0 1px;
  color: #999;
}

/* 提示文字样式 */
.upload-hint {
  font-size: 12px;
  color: #fc6666;
  line-height: 1.4;
  padding: 4px 0;
}
</style>
